//index.js
var t = getApp(),
    a = t.requirejs("core"),
    c = t.requirejs("api/index");
var loading = false;
Page({
  data: {
    ispreviewImage:false,
    cate_id: "",
    route: "card",
    menu: t.tabBar,
    menu_show: false,
    page: 1,
    list: [],
    loaded: [],
    show: false,
    display: false,
    showtabbar: false,
    show_chat: 0,
    show_comment: 1,
    tabbar_index: 0,
    config: t.config,
    card_id: 0 ,
    get_phone: true,
    tzuser_id:0,
    user_id: 0,
    search_val: '',
    cate_list:[],
    scroll_left: 0
  },
  selected:function(t){
    var that = this,
      index = a.pdata(t).index,
      cate_id = a.pdata(t).type;
    var acvive = a.pdata(t).acvive;
    if (acvive == 'actice') {
      return true;
    }
    that.setData({
      list:[],
      page: 1,
      loaded: false,
      cate_id: cate_id,
      scroll_left: index * 20
    });
    that.getlist();
  },
  onHide: function () {
    t.setCache('back_menu', 'mesaage', 2);
  },
  onGotUserInfo: function (q) {
    var that = this,
      e = t.getCache("userinfo");

    if (e) {
      that.setData({
        display: false
      })
      return;
    }
    t.getUserInfo(q.detail.userInfo, function (t) {
      if (t != 1000) {
        var ucache = getApp().getCache("userinfo");
        if (ucache) {
          getApp().get_news_num(that);
          that.setData({
            display: false,
            getPhoneAuth: getApp().globalData.getphone
          })
        }
      } else {
        that.setData({
          display: true
        })
      }

    }, q.detail.encryptedData, q.detail.iv);

  },

  // 授权获取用户信息判断
  authCheck: function () {
    var cache = getApp().getCache("userinfo");
    if (!cache.nickName && !cache.avatarUrl) {
      this.setData({
        display: true
      })
      return false;
    } else {
      this.setData({
        display: false
      })
      return true;
    }
  },

  // 取消登录
  cancel_auth: function () {
    this.setData({
      display: false
    })
  },

  //底部导航跳转
  menu_url: function (k) {
    a.menu_url(k, 2);
  },
  onLoad: function (ez) {
    // var hidet = t.getCache('hideTabBar');
    // if (!hidet) {
    //   wx.hideTabBar();
    //   t.setCache('hideTabBar', 111);
    // }
    var e = t.getCache("userinfo");
    var that = this;
    if (!e.nickName && !e.avatarUrl) {
      getApp().authSwitch(function(res){
        if (res == 1) {
          that.setData({
            display: true
          })
        } else {
          that.setData({
            display: false
          })
        }
      })
    }

    if (ez && ez.card_id) {
      t.globalData.card_id = ez.card_id;
    }
      a.setting();
      if (ez != null && ez != undefined) {
        that.setData({
          tabbar_index: ez.tabbar_index ? ez.tabbar_index : -1
        });
      }
      if (that.data.tabbar_index >= 0) {
        that.setData({
          showtabbar: getApp().tabBar.IsDiDis ? getApp().tabBar.IsDiDis : false,
        })
      }

  },
  onShow: function () {
    
    if (this.data.ispreviewImage) return this.setData({ ispreviewImage:false})
    console.log("重新加载。。。。。。。。。。。。。")
    var that=this;
      t.set_caidan(function () {
        that.setData({
          config: getApp().config
        })
      });
      t.get_news_num(that);
      if (that.card_id != t.globalData.card_id || t.globalData.card_id==0){
        that.setData({
        list: [],
        page: 1,
        loaded: false
      })
        that.getlist();
    }
    that.getMessageCate();
    that.setData({
        card_id: t.globalData.card_id,
        user_id: getApp().getCache('userinfo').uid != undefined ? getApp().getCache('userinfo').uid : 0,
    })
  },

  // 查询动态列表
  getlist: function () {
    if (loading) {
      return;
    }
    t.userlog(1, '动态', 'trends_browse');
    loading = true;
    var that = this,
      page = that.data.page;
    a.get('Card/message', {
      staff_id: t.globalData.card_id,
      page:that.data.page,
      class_id : that.data.cate_id,
      search_val: that.data.search_val
    }, function (t) {
      loading = false;
      if (t.code == 0) {
        that.setData({
          list: that.data.list.concat(t.info),
          page: t.info.length == 0 ? that.data.page : (that.data.page + 1),
          loaded: t.info.length < 10 ? true : false,
          show: true,
          show_chat: t.show_chat,
          show_comment: t.show_comment,
        })
      } else {
        a.alert(t.msg);
      }
    }, !that.data.show)
  },
  click: function (e) {
    var that = this,
      i = a.pdata(e).index;
    that.setData({
      hidden: i != that.data.hidden ? i : -1
    })
  },
  select: function (e) {
    var that = this,
      i = a.pdata(e).status;
    that.setData({
      page: 1,
      list: [],
      loaded: false,
      status: i
    })
    this.getlist()
  },

  // 获取用户手机号
  getMobile: function (e) {
    t.globalData.getphone = false;
    this.setData({
      getPhoneAuth: false
    })
    t.getPhoneNumber(e, this, 3);
  },

  previewImage: function (t) {
    var _this = this;
    var e = t.currentTarget.dataset.id, n = [], i = t.currentTarget.dataset.index, o = this.data.list;
    for (var s in o) if (o[s].id == e) {
      var r = o[s].pic_arr;
      console.log(r)
      for (var c in r) n.push( r[c]);
      wx.previewImage({
        current: r[i],
        urls: n,
        complete:function(){
          _this.setData({
            ispreviewImage:true
          })
        }
      });
    }
  },
  colse_more:function(e){
    var that = this,
      data = a.pdata(e),
      list = that.data.list;
    list[data.index].more = false;
    that.setData({
      list: list
    })
  },
  show_more: function (e) {
    var that = this,
      data = a.pdata(e),
      list = that.data.list;
      console.log(data)
    if (!data.more) {
      list.forEach(function (t) {
        t.more = false;
      })
    }
    list[data.index].more = data.more ? false : true;
    that.setData({
      list: list
    })
  },
  to_article: function (e) {
    var data = a.pdata(e), url = '';
    if (data.link) {
      url = '/yb_mingpian/pages/web/index?url=' + escape(data.link) + '&name=' + data.name;
    } else {
      url = '/yb_mingpian/pages/find_info/index?id=' + data.id;
    }
    this.setData({
      ispreviewImage:true
    })
    a.jump(url);

  },
  // 点赞
  thumbs_up: function (t) {
    var e = getApp().getCache("userinfo");
    if (!e) {
      this.setData({
        display: true
      })
      return;
    }
    var that = this,
     n = that.data.list, 
     index = t.currentTarget.dataset.index,
      i = t.currentTarget.dataset.id,
      o=getApp().getCache('userinfo');

    a.get('Card/Zan',{
      c_id: i,
      user_id: o.uid,
      type_zan: 2,
    }, function (t) {
      var nick_name = o.nickName ? o.nickName : '路人甲_' + o.uid;
      var avatar = o.avatarUrl ? o.avatarUrl : '/yb_mingpian/static/images/noface.png';

      if (t.code == 0) {
        a.success('点赞成功'), n[index].zan.unshift({ user_headimg: avatar, nick_name: nick_name });
      } else {
        a.toast('不能重复点赞');
      }
      n[index].more = !1,

      that.setData({
        list: n
      })
    })
    
  },

  // 删除评论
  delete_comment:function(e){
    var that = this,
        id = a.pdata(e).id,
        user_id = a.pdata(e).user_id,
        u_id = getApp().getCache('userinfo').uid,
        index = a.pdata(e).index,
        key = a.pdata(e).key;

    if (user_id != u_id || user_id == 0) {
      a.alert("没有权限");
      return false;
    }

    wx.showModal({
      title: '提示',
      content: '确认删除吗？',
      success: function (res) {
        if (!res.cancel) {
          a.get('Delete/Comment', {
            id: id,
            current_user_id: u_id,
            user_id: user_id
          }, function (res) {
            if (res.code == 1) {
              that.data.list[index]['comment'].splice(key, 1);
              that.setData({
                list: that.data.list
              })
            } else {
              a.alert("删除失败");
            }
          })
        }
      }
    })
  },

  //跳转+收集表单id
  formSubmit: function (k) {
    var e = {};
    e.formid = k.detail.formId;
    e.openid = getApp().getCache("userinfo").openid;
    e.username = getApp().getCache("userinfo").nickName;
    a.get('Market/getFormid', e, function (t) {
      console.log(t)
    })
    a.jump('/yb_mingpian/pages/chats/chats');
  },
  to_chat: function () {
    a.jump('/yb_mingpian/pages/chats/chats');
  },
  getPhoneNumber: function (e) {
    t.getPhoneNumber(e, this, 1);
  },
  comm: function (t) {
    var Cache =getApp().getCache("userinfo");
    if (!Cache) {
      this.setData({
        display: true
      })
      return;
    }
    var that = this,
      n = that.data.list,
      data = a.pdata(t);
    n[data.index].more = !1,
      that.setData({
        comm: true,
        list: n,
        in_id: data.id,
      tzuser_id: getApp().getCache('userinfo').uid,
        comm_index: data.index
      })
  },
  show_comm: function () {
    
    this.setData({
      comm: false
    })
  },

  // 发表评论
  comm_submit: function (e) {
    var that = this,
        user = t.getCache('userinfo'),
        list = that.data.list,
        data = e.detail.value;

    if (loading) {
        return;
    }

    if (!user) {
        return;
    }

    var nick_name = user.nickName ? user.nickName : '路人甲_' + user.uid;

    loading=true;
      a.loading('评论提交中');
    a.get('Card/Comment',{
      in_id: data.in_id,
      details: data.content,
      user_id: user.uid,
    },function(t){
      a.hideLoading();
      loading = false;
      var e = { comm: false };
      if(t.code==0){
        list[data.index].comment.unshift({ id: t.info, details: data.content, nick_name: nick_name, user_id: user.uid });
        e.list = list;
        that.setData(e)
        a.success('评论成功');
        console.log(that.data.list);
      }else{
        a.alert(t.msg);
      }
  
    })
  },

  /**
   * 搜索查询
   */
  bindSearch: function() {
    var search_val = this.data.search_val;

    if (search_val.length > 0) {
      this.setData({
        list: [],
        loading: true,
        page: 1,
      })

      this.getlist();
    }
  },

  /**
   * 动态获取搜索的值
   */
  inputing:function(val){
    // 去除两边空格
    var search_val = val.detail.value.replace(/\s+/g, '');
    this.setData({
      search_val: search_val
    })
  },

  /**
   * 取消搜索
   */
  searchCancel:function(){
      this.setData({
        list: [],
        loading: true,
        page: 1,
        search_val: ''
      })

      this.getlist();
  },

  /**
    * 下拉刷新
    */
  onPullDownRefresh: function () {
    this.setData({
      list: [],
      page: 1,
      loaded: false
    })
    this.getMessageCate();
    this.getlist();
    wx.stopPullDownRefresh();
  },
  getMessageCate:function(){
    var that = this;
    a.get('Message/cate', {
    }, function (t) {
      if (t.code == 0) {
        that.setData({
          cate_list: t.info,
        })
      } else {
        a.alert(t.msg);
      }
    })
  },
  /**
   *上拉加载
   */
  onReachBottom: function () {
    console.log('加载更多')
    this.data.loaded || this.getlist()
  },
  tap_copy:function(t){
    let that = this.data;
    let index = a.pdata(t).index;
    let info = that.list[index];
    //先复制
    if (info.article && info.article.image){
      //复制文章
      wx.getSetting({
        success: function (t) {
          t.authSetting["scope.writePhotosAlbum"] ? (wx.showLoading({
            title: "图片下载中",
            mask: !0
          }), wx.getImageInfo({
            src: info.article.image,
            success: function (t) {
              wx.saveImageToPhotosAlbum({
                filePath: t.path,
                success: function (t) {
                  wx.setClipboardData({
                    data: info.article.title
                  }); 
                  wx.hideLoading();
                   wx.showModal({
                    title: "提示",
                    content: "文案已复制，图片已保存至系统相册",
                    showCancel: !1
                  });
                }
              });
            },
            fail: console.error
          })) : wx.authorize({
            scope: "scope.writePhotosAlbum"
          });
        }
      });
    }else{
      //复制动态
      let pics = info.pic_arr;
      if(pics.length){ //批量下载图片
          for(var i=0 ;i <pics.length ;i++){
            console.log('正在下载第'+i+"张图片")
            let src = pics[i];
            let num = i;
            wx.getSetting({
              success: function (t) {
                t.authSetting["scope.writePhotosAlbum"] ? (wx.showLoading({
                  title: "图片下载中",
                  mask: !0
                }), wx.getImageInfo({
                  src: src,
                  success: function (t) {
                    wx.saveImageToPhotosAlbum({
                      filePath: t.path,
                      success: function (t) {
                       
                        if (num + 1 == pics.length){
                          wx.setClipboardData({
                            data: info.content,
                            success: function () {
                              wx.hideLoading();
                              wx.showModal({
                                title: "提示",
                                content: "文案已复制，图片已保存至系统相册",
                                showCancel: !1
                              });
                            }
                          }); 
                        }
                      }
                    });
                  },
                  fail: function(res){
                    console.log(res)
                    console.error
                    wx.hideLoading();
                  }
                })) : wx.authorize({
                  scope: "scope.writePhotosAlbum"
                });
              }
            });
          }
      }
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this.data,
      uid = getApp().getCache('userinfo').uid ? getApp().getCache('userinfo').uid : 0;

    t.userlog(2, '动态', 'trends_relay');
    let path = '/yb_mingpian/pages/message/index?pid=' + uid + "&card_id=" + t.globalData.card_id;
    let share_name = that.name;
    let imagUrl = '';
    if (res.from  == "button"){
      let index = res.target.dataset.index;
      let info = that.list[index];
      if(info.article_id > 0){
        path = '/yb_mingpian/pages/find_info/index?pid=' + uid + "&card_id=" +      t.globalData.card_id + "&id=" + info.article_id;
        imagUrl = info.article.image;
        share_name = info.article.title;
      }else{
        if (info.pic_arr.length) {
          imagUrl = info.pic_arr[0];
        }
        share_name = that.list[index].content;
      }
    }
    return {
      title: share_name,
      path: path,
      imageUrl: imagUrl,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})